from django.db import models
from django.utils import timezone
from user_auth.models import User
from django.conf import settings
import os
from PIL import Image
import boto3
from botocore.exceptions import ClientError

class Note(models.Model):
    """笔记模型"""
    id = models.BigAutoField(primary_key=True)
    title = models.CharField(max_length=200, verbose_name='标题')
    content = models.TextField(verbose_name='内容')
    cover_image = models.ImageField(
        upload_to='note_covers/', 
        blank=True, 
        null=True,
        verbose_name='封面图片'
    )
    author = models.ForeignKey(
        User, 
        on_delete=models.CASCADE, 
        related_name='notes',
        verbose_name='作者'
    )
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    is_public = models.BooleanField(default=True, verbose_name='是否公开')
    likes_count = models.IntegerField(default=0, verbose_name='点赞数')
    
    class Meta:
        verbose_name = '笔记'
        verbose_name_plural = '笔记'
        ordering = ['-created_at']
    
    def __str__(self):
        return self.title
    
    def save(self, *args, **kwargs):
        # 处理封面图片（可选：压缩图片）
        if self.cover_image:
            # 获取原始图片路径
            original_path = self.cover_image.path
            
            # 使用Pillow压缩图片
            img = Image.open(original_path)
            # 限制图片大小为1024x1024
            img.thumbnail((1024, 1024))
            img.save(original_path, optimize=True, quality=85)
        
        super().save(*args, **kwargs)
    
    def delete(self, *args, **kwargs):
        # 删除封面图片
        if self.cover_image:
            if os.path.exists(self.cover_image.path):
                os.remove(self.cover_image.path)
        
        super().delete(*args, **kwargs)

class Like(models.Model):
    """点赞模型"""
    id = models.BigAutoField(primary_key=True)
    user = models.ForeignKey(
        User, 
        on_delete=models.CASCADE, 
        related_name='likes',
        verbose_name='点赞用户'
    )
    note = models.ForeignKey(
        Note, 
        on_delete=models.CASCADE, 
        related_name='likes',
        verbose_name='点赞笔记'
    )
    created_at = models.DateTimeField(default=timezone.now, verbose_name='点赞时间')
    
    class Meta:
        verbose_name = '点赞'
        verbose_name_plural = '点赞'
        # 确保每个用户对每个笔记只能点赞一次
        unique_together = ('user', 'note')
    
    def __str__(self):
        return f"{self.user.username} 点赞了 {self.note.title}"
    
    def save(self, *args, **kwargs):
        # 增加笔记的点赞数
        self.note.likes_count += 1
        self.note.save()
        super().save(*args, **kwargs)
    
    def delete(self, *args, **kwargs):
        # 减少笔记的点赞数
        if self.note.likes_count > 0:
            self.note.likes_count -= 1
            self.note.save()
        super().delete(*args, **kwargs)